package cn.wolfcode.mq.listener;

import cn.wolfcode.domain.OperateIntergralVo;
import cn.wolfcode.domain.OrderInfo;
import cn.wolfcode.service.IOrderInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

@Slf4j
@RocketMQTransactionListener(txProducerGroup = "tx_group")
@Component
public class OrderTXMsgListener implements RocketMQLocalTransactionListener {
    @Autowired
    private IOrderInfoService orderInfoService;
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        log.info("执行本地事务");
        RocketMQLocalTransactionState result = RocketMQLocalTransactionState.COMMIT;
        try {
            String orderNo = (String) arg;
            orderInfoService.changeOrderStatus(orderNo);
        } catch (Exception e) {
            result = RocketMQLocalTransactionState.UNKNOWN;
        }
        return result;
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        log.info("检查本地事务");
        RocketMQLocalTransactionState result = RocketMQLocalTransactionState.COMMIT;
        try{
            OperateIntergralVo vo = (OperateIntergralVo) msg.getPayload();
            Integer status = orderInfoService.getOrderStatus(vo.getPk());
            if(!OrderInfo.STATUS_REFUND.equals(status)){
                result = RocketMQLocalTransactionState.ROLLBACK;
            }
        }catch(Exception e){
            result = RocketMQLocalTransactionState.ROLLBACK;
        }
        return result;
    }
}